package com.stn.zjx.givingtreasure.activity.dynamic;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.irozon.sneaker.Sneaker;
import com.irozon.sneaker.interfaces.OnSneakerDismissListener;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.UserLoginActivity;
import com.stn.zjx.givingtreasure.adapter.DynamicGuestGuestReplyAdapter;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.bean.DynamicGuest;
import com.stn.zjx.givingtreasure.domain.DynamicGuestGuestReplyDomain;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.RefreshEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicGuestGuestNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicGuestLikeNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.SoftInputUtils;
import com.stn.zjx.givingtreasure.utils.StatusBarUtil;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class DynamicDetailReplyActivity extends BaseActivity {
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.reply_tv)
    TextView replyTv;
    @BindView(R.id.open_guest)
    LinearLayout openGuest;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.cir)
    CircleImageView cir;
    @BindView(R.id.user_nickname)
    TextView userNickname;
    @BindView(R.id.good_iv)
    ImageView goodIv;
    @BindView(R.id.good_num)
    TextView goodNum;
    @BindView(R.id.good_bt)
    RelativeLayout goodBt;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.date_time)
    TextView dateTime;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.no_data)
    LinearLayout noData;
    @BindView(R.id.bottom_loading_tv)
    TextView bottomLoadingTv;
    @BindView(R.id.bottom_loading)
    RelativeLayout bottomLoading;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.twinkling_refresh)
    TwinklingRefreshLayout twinklingRefresh;
    public DynamicGuest data;
    @BindView(R.id.guest_guest_title)
    TextView guestGuestTitle;
    private LinearLayoutManager lm;
    private DynamicGuestGuestReplyAdapter adapter;
    public int pageNow = 1;
    public int pageSize = 10;
    public boolean isMoreLoading = false;
    //登录刷新
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFragmentLoginRefresh(RefreshEvent event) {
        if (event.flag == RefreshEvent.LOGIN_REFRESH) {
         //   initInfo();
            initData();
        }else if(event.flag==RefreshEvent.REFRESH){
            initData();
        }
    }

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }




    @Override
    public void initComponent() {
        actionTitle.setVisibility(View.VISIBLE);
        actionTitle.setText(getString(R.string.reply_details));
        data = (DynamicGuest) getIntent().getSerializableExtra("data");
        lm = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rv.setLayoutManager(lm);
        rv.setAdapter(adapter = new DynamicGuestGuestReplyAdapter(this));
        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY == (nestedScrollView.getChildAt(0).getMeasuredHeight() - nestedScrollView.getMeasuredHeight())) {
                    if(!isMoreLoading&&adapter.dataBeanList.size()>=pageNow*pageSize){
                        User onlineUser = UserService.getInstance(getApplicationContext()).getOnlineLoginUser();
                        String token = "";
                        if (onlineUser == null) {
                            token = "";
                        } else {
                            token = onlineUser.getToken();
                        }
                        query_dynamic_guest_guest_append(token,data.getUserDynamicGuestId());
                    }
                }

            }
        });
        if (data != null) {
            initInfo();
            initData();
        }
    }

    public void initInfo() {
         replyTv.setText(""+getString(R.string.reply)+": "+data.getUserNickname());
        guestGuestTitle.setText("0"+getString(R.string.strip)+getString(R.string.reply));
        Glide
                .with(this)
                .asDrawable()
                .load(data.getUserAvatar())
                .apply(new RequestOptions().placeholder(R.mipmap.default_avatar))
                .transition(DrawableTransitionOptions.withCrossFade(500))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        cir.setImageDrawable(resource);
                    }
                });
        userNickname.setText(data.getUserNickname());
        goodNum.setText(String.valueOf(data.getGuestlikeCount()));

        content.setText(data.getUserDynamicGuestContent());
        switch (data.getGuestisLike()) {
            case 0:
                goodIv.setImageResource(R.mipmap.good_noselect);
                break;
            case 1:
                goodIv.setImageResource(R.mipmap.good_select);
                break;
        }
        goodBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User onlineUser = UserService
                        .getInstance(getApplicationContext())
                        .getOnlineLoginUser();
                if (onlineUser == null) {
                    RxActivityTool.skipActivity(getApplicationContext(), UserLoginActivity.class);
                    return;
                }
                switch (data.getGuestisLike()) {
                    case 0:
                        goodIv.setImageResource(R.mipmap.good_select);
                        goodNum.setText(String.valueOf(data.getGuestlikeCount() + 1));
                        data.setGuestisLike(1);
                        data.setGuestlikeCount(data.getGuestlikeCount() + 1);
                        set_like_dynamic_guest(onlineUser.getToken(), data.getUserDynamicGuestId());
                        break;
                    case 1:
                        goodIv.setImageResource(R.mipmap.good_noselect);
                        goodNum.setText(String.valueOf(data.getGuestlikeCount() - 1));
                        data.setGuestisLike(0);
                        data.setGuestlikeCount(data.getGuestlikeCount() - 1);
                        set_no_like_dynamic_guest(onlineUser.getToken(), data.getUserDynamicGuestId());
                        break;
                }
            }
        });
        dateTime.setText(ToolsUtils.getDateBeforeAfter(data.getUserDynamicGuestCreatedate()));

       openGuest.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               initGuestDialog(data.getUserDynamicGuestId(),0,data.getUserNickname());
           }
       });
    }

    public void initData() {

        User onlineUser = UserService.getInstance(this).getOnlineLoginUser();
        String token = "";
        if (onlineUser == null) {
            token = "";
        } else {
            token = onlineUser.getToken();
        }
        query_dynamic_guest_guest(token,data.getUserDynamicGuestId());

    }

    //动态评论点赞
    public void set_like_dynamic_guest(String token, Integer userDynamicGuestId) {
        UserDynamicGuestLikeNetImpl
                .set_like_dynamic_guest(token, userDynamicGuestId, token + "_set_like_dynamic_guest_" + userDynamicGuestId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    //动态评论取消点赞
    public void set_no_like_dynamic_guest(String token, Integer userDynamicGuestId) {
        UserDynamicGuestLikeNetImpl
                .set_no_like_dynamic_guest(token, userDynamicGuestId, token + "_set_no_like_dynamic_guest_" + userDynamicGuestId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_detail_guest_reply);
        ButterKnife.bind(this);
        StatusBarUtil.setImmersiveStatusBar(this, true);
        initStatusBarColor(R.color.transparentBlank_5);
        initComponent();
    }

    //

    //分页查询评论回复
    public void query_dynamic_guest_guest(String token, Integer userDynamicGuestId
    ) {
        pageNow = 1;
        UserDynamicGuestGuestNetImpl
                .query_dynamic_guest_guest(token, userDynamicGuestId, pageNow, pageSize,
                        token + "_query_dynamic_guest_guest_" + userDynamicGuestId + "_" + pageNow,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                bottomLoading.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                bottomLoading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    Gson gson = new Gson();
                                    DynamicGuestGuestReplyDomain domain = gson.fromJson(response.body(), DynamicGuestGuestReplyDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            if (domain.getData() != null &&
                                                    domain.getData().getGuestGuests() != null
                                                    && domain.getData().getGuestGuests().size() != 0) {
                                                noData.setVisibility(View.GONE);
                                                guestGuestTitle.setText(domain.getData().getGuestGuestsCount()+""+getString(R.string.strip)+getString(R.string.reply));
                                                guestGuestTitle.setVisibility(View.VISIBLE);
                                                adapter.refreshList(domain.getData().getGuestGuests());
                                            } else {
                                                guestGuestTitle.setVisibility(View.GONE);
                                                noData.setVisibility(View.VISIBLE);
                                            }
                                            break;
                                         default:
                                             guestGuestTitle.setVisibility(View.GONE);
                                             noData.setVisibility(View.GONE);
                                             break;
                                    }


                                }
                            }

                        });

    }

    //分页查询评论回复,追加
    public void query_dynamic_guest_guest_append(String token, Integer userDynamicGuestId
    ) {
        pageNow ++;
        UserDynamicGuestGuestNetImpl
                .query_dynamic_guest_guest(token, userDynamicGuestId, pageNow, pageSize,
                        token + "_query_dynamic_guest_guest_" + userDynamicGuestId + "_" + pageNow,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                isMoreLoading=true;
                                bottomLoading.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                isMoreLoading=false;
                                bottomLoading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    Gson gson = new Gson();
                                    DynamicGuestGuestReplyDomain domain = gson.fromJson(response.body(), DynamicGuestGuestReplyDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            if (domain.getData() != null &&
                                                    domain.getData().getGuestGuests() != null
                                                    && domain.getData().getGuestGuests().size() != 0) {

                                                adapter.appendList(domain.getData().getGuestGuests());
                                            }

                                            break;
                                    }


                                }
                            }

                        });

    }
    @OnClick({R.id.back_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;

        }
    }



    public void initGuestDialog(Integer userDynamicGuestId,Integer toUserId,String userNickname) {
        Dialog guest_dialog;
        EditText guest_content_edit;
        guest_dialog = new Dialog(this, R.style.dialog_soft_input);
        guest_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        guest_dialog.setContentView(R.layout.dialog_dynamic_guest_input);
        WindowManager.LayoutParams lp = guest_dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.BOTTOM;
        guest_dialog.getWindow().setAttributes(lp);

        guest_content_edit = guest_dialog.findViewById(R.id.content_edit);
        guest_content_edit.setHint(""+getString(R.string.reply)+" "+userNickname);
        guest_content_edit.setHintTextColor(ActivityCompat.getColor(this,R.color.gray));
        TextView guest_num_count = guest_dialog.findViewById(R.id.num_count);
        TextView guest_send_guest_bt = guest_dialog.findViewById(R.id.send_guest_bt);
        View exit_bt = guest_dialog.findViewById(R.id.exit_bt);
        exit_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                guest_dialog.dismiss();
            }
        });
        guest_dialog.findViewById(R.id.rootView)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        guest_dialog.dismiss();
                    }
                });
        guest_content_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                guest_num_count.setText(guest_content_edit.getText().length() + "/100");
                if (guest_content_edit.getText().length() == 0) {
                    guest_send_guest_bt.setBackgroundResource(R.drawable.focus_light_gray_5dp);
                    guest_send_guest_bt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.gray));
                    guest_send_guest_bt.setClickable(false);
                } else {
                    guest_send_guest_bt.setBackgroundResource(R.drawable.focus_theme_5dp);
                    guest_send_guest_bt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.white));
                    guest_send_guest_bt.setClickable(true);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        guest_send_guest_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User onlineUser = UserService
                        .getInstance(getApplicationContext())
                        .getOnlineLoginUser();
                if (onlineUser == null) {
                    RxActivityTool.skipActivity(getApplicationContext(), UserLoginActivity.class);
                    return;
                }

                send_dynamic_guest_guest(onlineUser.getToken(),
                        toUserId,
                        userDynamicGuestId,
                        guest_content_edit.getText().toString().trim(),
                        guest_dialog);
            }
        });
        guest_send_guest_bt.setClickable(false);
        guest_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //    guest_content_edit.getText().clear();
                // 显示软键盘
                guest_content_edit.requestFocus();
                SoftInputUtils.openSoftInput(DynamicDetailReplyActivity.this,guest_dialog.getCurrentFocus(),50);
                //  SoftInputUtils.showSoftInput(DynamicDetailActivity.this,guest_dialog);
            }
        });
        guest_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                    SoftInputUtils.closedSoftInput(DynamicDetailReplyActivity.this);
                guest_content_edit.getText().clear();
            }
        });
        guest_dialog.show();
    }

    //发送动态评论
    public void send_dynamic_guest_guest(String token,
                                         Integer toUserId,
                                         Integer userDynamicGuestId,
                                         String userDynamicGuestGuestContent,Dialog dialog) {
        UserDynamicGuestGuestNetImpl
                .send_dynamic_guest_guest(token, toUserId, userDynamicGuestId,
                        userDynamicGuestGuestContent,
                        token + "_send_dynamic_guest_guest_" + userDynamicGuestId,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            dialog.dismiss();
                                            RefreshEvent event=new RefreshEvent();
                                            event.flag=RefreshEvent.REFRESH;
                                            EventBus.getDefault().post(event);
//                                            Sneaker.with(DynamicDetailReplyActivity.this)
//                                                    .autoHide(true)
//                                                    .setTitle(""+domain.getMessage(),R.color.white)
//                                                    .sneakSuccess();

                                            break;
                                         default:
//                                             Sneaker.with(DynamicDetailReplyActivity.this)
//                                                     .autoHide(true)
//                                                     .setTitle(""+domain.getMessage(),R.color.white)
//                                                     .sneakError();
                                             showToast(domain.getMessage());
                                             break;
                                    }


                                }
                            }
                        });

    }
}
